package util

import (
	"bufio"
	"encoding/json"
	"io"
	"os"
	"path/filepath"
)

type Resource struct {
	root string
}

var ProcessDir = Resource{
	root: filepath.Dir(os.Args[0]),
}

func (o *Resource) Root(dir string) {
	if filepath.IsAbs(dir) {
		o.root = dir
	} else {
		o.root = o.Abs(dir)
	}
}

func (o *Resource) Abs(dirs ...string) string {
	public := filepath.Join(dirs...)
	return filepath.Join(o.root, public)
}

func (o *Resource) String() string {
	return o.root
}

// JSONFile
func JSONFile(filename string, v interface{}) error {
	jsonFp, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer jsonFp.Close()
	var jsString string
	iReader := bufio.NewReader(jsonFp)
	for {
		tString, err := iReader.ReadString('\n')
		if err == io.EOF {
			break
		}
		jsString = jsString + tString
	}
	return json.Unmarshal([]byte(jsString), v)
}

// func YamlFile(filename string, v interface{}) error {
// 	b, err := os.ReadFile(filename)
// 	if err != nil {
// 		return err
// 	}
// 	return yaml.Unmarshal(b, v)
// }
